package com.example.chatweb.controller;

import com.example.chatweb.entity.Tag;
import com.example.chatweb.mapper.TagMapper;
import com.example.chatweb.request.InsertTagRequest;
import com.example.chatweb.service.TagService;
import com.example.chatweb.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

@RestController
public class TagController {
    private final TagService tagService;
    @Autowired
    private final TagMapper tagMapper;


    @Autowired
    public TagController(TagService tagService, TagMapper tagMapper) {
        this.tagService = tagService;
        this.tagMapper = tagMapper;
    }

    public boolean saveUniqueTags(List<Tag> tags) {
        // 获取数据库中已存在的用户
        List<Tag> existingTags = tagMapper.selectList(null);
        List<String> existingTagLabel = existingTags.stream()
                .map(Tag::getLabel)
                .collect(Collectors.toList());

        // 过滤掉已存在的用户
        List<Tag> newTags = tags.stream()
                .filter(tag -> !existingTagLabel.contains(tag.getLabel()))
                .collect(Collectors.toList());

        // 批量插入新的用户
        if (!newTags.isEmpty()) {
            System.out.println("输出");
            System.out.println(newTags);
            return tagService.saveBatch(newTags);
        }
        return true;
    }

    @PostMapping("/add_entity_type")
    public R addTags(@RequestBody InsertTagRequest insertTagRequest) {
        System.out.println(insertTagRequest.getTags());
        boolean i = saveUniqueTags(insertTagRequest.getTags());
        System.out.println(insertTagRequest.getTags());
        if(i){
            return R.ok("添加实体类别成功");
        }else{
            return R.failure("添加实体类别失败");
        }
    }
}
